package com.shujia.day19.mysql.pool;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Operator {
    public static void main(String[] args) throws Exception {
        /*
            TODO 使用连接池
         */
        MySqlConnectionPool mysqlConPool = MysqlConPoolManager.createMysqlConPool("resource/mysql_pool.properties");
        MysqlConnection oneCon = MysqlConPoolManager.getOneCon();
        MysqlConPoolManager.releaseMysqlCon(oneCon);

        UseMysql useMysql = new UseMysql(mysqlConPool);
        for (int i = 0; i < 11; i++) {
            new Thread(useMysql,"线程"+(i+1)).start();
        }
        while (true){}

    }

    static class UseMysql implements Runnable {
        MySqlConnectionPool mysqlConPool;

        public UseMysql(MySqlConnectionPool mysqlConPool) {
            this.mysqlConPool = mysqlConPool;
        }

        @Override
        public void run() {
            MysqlConnection mysqlCon = mysqlConPool.getMysqlCon();
            Statement statement = null;
            Thread thread = Thread.currentThread();
            try {
                statement = mysqlCon.connection.createStatement();
                ResultSet resultSet = statement.executeQuery("select * from students limit 10");
                while (resultSet.next()) {
                    // resultSet中的位置下标是从1开始 不能给定0
                    String id = resultSet.getString(1);
                    String name = resultSet.getString(2);
                    int age = resultSet.getInt(3);
                    String gender = resultSet.getString(4);
                    String clazz = resultSet.getString(5);
                    System.out.println(thread.getName() + "\t" + id + "\t" + name + "\t" + age + "\t" + gender + "\t" + clazz);
                }
                mysqlConPool.releaseMysqlCon(mysqlCon);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
